package cn.calm.xhtml.impl.ui;

import java.util.Collection;

import cn.calm.xhtml.annotation.Attribute;
import cn.calm.xhtml.annotation.Tag;
import cn.calm.xhtml.api.exception.XhtmlException;
import cn.calm.xhtml.api.service.AbstraceNodeProcess;
import cn.calm.xhtml.api.service.ResponseWriter;
import cn.calm.xhtml.api.service.XhtmlContext;
@Tag(namespace = "http://www.calm.cn/xhtml/extras/ui", attributes = {
		@Attribute(name = "label", description = "标签", template = "<label></label><input name=\"label\"/>"),
		@Attribute(name = "items", description = "列表选项", template = "<label></label><input name=\"items\"/>") })
public class OptionGroup extends AbstraceNodeProcess {
	public static final String KEYS_LABEL = "label";

	public static final String KEYS_ITEMS = "items";
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	@Override
	public void processNode(XhtmlContext context) throws XhtmlException {
		ResponseWriter writer = context.getResponseWriter();
		writer.startTag("optgroup");
		writeAttr(context, "label", KEYS_LABEL);
		writeAttr(context, "value", "value");
		writer.write(">");
		Object items = getAttrValue(KEYS_ITEMS, context);
		
		Collection<?> ite = convertCollection(items);
		Object childrenProperty = getAttrValue(Select.KEYS_CHILDREN_PROPERTY, context);
		
		String property = getAttr(Select.KEYS_VALUE_PROPERTY);
		if (property == null) {
			throw new XhtmlException();
		}
		String text = getAttr(Select.KEYS_TEXT_PROPERTY);
		if (text == null) {
			throw new XhtmlException();
		}
		if (childrenProperty == null) {
			for (Object o : ite) {
				Select.processOption(context, property, text, o);
			}
		} else {
			for (Object o : ite) {
				Select.processOptionGroup(context, property, text, items,
						childrenProperty, o);
			}
		}
		writer.endTag("optgroup");
	}
	
}


